package algo.ch0103;

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author mougua
 */
public class ResizingArrayStack<E> implements Iterable<E>{
    private E[] a;
    private int n;

    @SuppressWarnings("unchecked")
    public ResizingArrayStack(int cap) {
        a = (E[]) new Object[cap];
    }

    public boolean isEmpty() {
        return n == 0;
    }

    public int size() {
        return n;
    }

    public void push(E e) {
        if (n == a.length) {
            resize(2 * a.length);
        }
        a[n++] = e;
    }

    public E pop() {
        E e = a[--n];
        a[n] = null;
        if (n > 0 && n == a.length/4) {
            resize(a.length/2);
        }
        return e;
    }

    @Override
    public String toString() {
        return "ResizingArrayStack{" +
                "a=" + Arrays.toString(a) +
                ", N=" + n +
                '}';
    }

    @SuppressWarnings("unchecked")
    private void resize(int max) {
        E[] temp = (E[]) new Object[max];
        if (n >= 0) {
            System.arraycopy(a, 0, temp, 0, n);
        }
        a = temp;
    }

    @Override
    public Iterator<E> iterator() {
        return new ReverseArrayIterator();
    }

    private class ReverseArrayIterator implements Iterator<E> {
        private int i = n;

        @Override
        public boolean hasNext() {
            return i > 0;
        }

        @Override
        public E next() throws NoSuchElementException {
            if (--i == 0) {
                throw new NoSuchElementException();
            }
            return a[i];
        }


        @Override
        public void remove() {

        }

    }
}
